package com.example.victory.utils;

import com.example.victory.config.ServiceError;
import com.example.victory.service.MvpLoginService;
import com.cgws.fintech.sdk.api.inner.security.model.User;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQuery;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQueryData;
import com.cgws.fintech.sdk.api.mvp.model.ApiResponseCustomerQuery;
import com.cgws.fintech.sdk.api.mvp.model.CustomerAccount;
import com.example.victory.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
public class CrmUtils {
	/**
	 * 根据客户号获取对应的imId
	 *
	 * @param mvpLoginService       mvpLoginService
	 * @param customerQueryDataList 客户号集合
	 * @return 账号信息集合
	 */
	public static List<CustomerAccount> getCustAccountListByIds(MvpLoginService mvpLoginService, List<ApiRequestCustomerQueryData> customerQueryDataList) {
		ApiRequestCustomerQuery customerQuery = new ApiRequestCustomerQuery();
		customerQuery.setData(customerQueryDataList);
		ResponseEntity<ApiResponseCustomerQuery> customerQueryResponseEntit = null;
		try {
			customerQueryResponseEntit = mvpLoginService.queryQustomers(customerQuery);
		} catch (Exception ex) {
			// 不抛出错误，让客户其它信息能正常返回
			log.error("请求mvp获取客户im号错误,e={}", ex);
		}
		if (customerQueryResponseEntit.getStatusCode() == HttpStatus.OK && customerQueryResponseEntit.getBody() != null) {
			List<CustomerAccount> customerAccountList = customerQueryResponseEntit.getBody().getData().getList();
			if (customerAccountList != null && customerAccountList.size() > 0) {
				return customerAccountList;
			}
		}
		return null;
	}

	/**
	 * 获取crmId
	 *
	 * @param user 会话里的user
	 * @return crmId
	 */
	public static Integer getCustomerAccount(User user) {
		String crmId = user.getCrmId();
		if (StringUtils.isEmpty(crmId)) {
			throw new GlobalException(ServiceError.ACCOUNT_NOT_EXISTS);
		}
		return Integer.parseInt(crmId);
	}
}
